package com.heatingcharge.service.unit.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.heatingcharge.common.exception.BaseException;
import com.heatingcharge.common.util.BeanValidator;
import com.heatingcharge.common.util.ResponseCodeEnum;
import com.heatingcharge.dto.ResBuildingDTO;
import com.heatingcharge.dto.ResUnitDTO;
import com.heatingcharge.dto.ZoneClearOffDTO;
import com.heatingcharge.entity.unit.ResBuilding;
import com.heatingcharge.mapper.unit.ResBuildingMapper;
import com.heatingcharge.param.ResBuildingParam;
import com.heatingcharge.param.SearchParam;
import com.heatingcharge.service.charge.IClearOffService;
import com.heatingcharge.service.unit.IResBuildingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heatingcharge.service.unit.IResUnitService;
import com.heatingcharge.vo.TreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 楼  服务实现类
 * </p>
 *
 * @author devin.jiang
 * @since 2019-07-12
 */
@Service
public class ResBuildingServiceImpl extends ServiceImpl<ResBuildingMapper, ResBuilding> implements IResBuildingService {

    @Autowired
    IResUnitService resUnitService;
    @Autowired
    IClearOffService clearOffService;

    @Override
    public IPage<ResBuilding> selectBuildingPage(Page page, ResBuildingDTO resBuildingDTO) {
        return baseMapper.selectBuilding(page, resBuildingDTO);
    }

    @Override
    public List<TreeVo> selectBuildingTree(ResBuildingDTO resBuildingDTO) {
        List<ResBuilding> resBuildings = baseMapper.selectBuilding(resBuildingDTO);
        List<TreeVo> treeVos = Lists.newArrayList();
        TreeVo treeVo;
        ResUnitDTO resUnitDTO;
        if (resBuildings.size() > 0) {
            for (int i = 0; i < resBuildings.size(); i++) {
                if (resBuildingDTO.getShowUnit().equals(false)) {
                    treeVo = TreeVo.builder()
                            .value(resBuildings.get(i).getId())
                            .id("buildId=" + resBuildings.get(i).getId())
                            .label(resBuildings.get(i).getNum())
                            .type("building")
                            .build();
                } else {
                    resUnitDTO = ResUnitDTO.builder()
                            .buildId(resBuildings.get(i).getId())
                            .build();
                    treeVo = TreeVo.builder()
                            .value(resBuildings.get(i).getId())
                            .id("buildId=" + resBuildings.get(i).getId())
                            .label(resBuildings.get(i).getNum())
                            .type("building")
                            .children(resUnitService.selectResUnitTree(resUnitDTO))
                            .build();
                }
                if (resBuildingDTO.getShowStatistics().equals(true)){
                    SearchParam searchParam=new SearchParam(0,resBuildings.get(i).getId(),resBuildingDTO.getHeatYearId());
                    ZoneClearOffDTO allZonesStatistics = clearOffService.getAllZonesStatistics(searchParam);
                    treeVo.setZoneClearOffDTO(allZonesStatistics);
                }
                treeVos.add(treeVo);
            }
        }
        return treeVos;
    }

    @Override
    public List<ResBuilding> selectBuildingByZoneId(ResBuildingDTO resBuildingDTO) {
        return baseMapper.selectBuilding(resBuildingDTO);
    }

    @Override
    public boolean save(ResBuildingParam resBuildingParam) {
        //校验字段合法性
        BeanValidator.check(resBuildingParam);
        //检验楼栋是否已经存在
        if (checkExist(resBuildingParam.getZoneId(), resBuildingParam.getNum(), null)) {
            //楼栋已经存在
            throw new BaseException(ResponseCodeEnum.RESBUILDING_EXIST.getMessage(), ResponseCodeEnum.RESBUILDING_EXIST.getCode());
        }
        ResBuilding resBuilding = ResBuilding.builder()
                .num(resBuildingParam.getNum())
                .zoneId(resBuildingParam.getZoneId())
                .stationId(resBuildingParam.getStationId())
                .build();
        return baseMapper.insert(resBuilding) > 0;
    }

    /**
     * 指定楼栋中是否存在指定楼栋
     *
     * @param zoneId 楼栋ID
     * @param num
     * @param id
     * @return
     */
    private boolean checkExist(Integer zoneId, String num, Integer id) {
        QueryWrapper<ResBuilding> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("zone_id", zoneId);
        queryWrapper.eq("u_num", num);
        if (id != null) {
            queryWrapper.ne("id", id);
        }
        return this.list(queryWrapper).size() > 0;
    }

    @Override
    public boolean update(ResBuildingParam resBuildingParam) {
        //校验字段合法性
        BeanValidator.check(resBuildingParam);
        //检验楼栋是否已经存在
        if (checkExist(resBuildingParam.getZoneId(), resBuildingParam.getNum(), resBuildingParam.getId())) {
            //楼栋已经存在
            throw new BaseException(ResponseCodeEnum.RESBUILDING_EXIST.getMessage(), ResponseCodeEnum.RESBUILDING_EXIST.getCode());
        }
        ResBuilding before = this.getById(resBuildingParam.getId());
        if (ObjectUtil.isNull(before)) {
            throw new BaseException(ResponseCodeEnum.RESBUILDING_NON_EXIST.getMessage(), ResponseCodeEnum.RESBUILDING_NON_EXIST.getCode());
        }
        ResBuilding after = new ResBuilding();
        BeanUtils.copyProperties(resBuildingParam, after);

        return baseMapper.updateById(after) > 0;
    }

    @Override
    public boolean removeById(Serializable id) {

        return super.removeById(id);
    }
}
